package com.ln.controller.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.WebUtils;

import com.ln.common.EmailValidator;
import com.ln.common.MD5;
import com.ln.pojo.impl.UserPOJO;
import com.ln.service.impl.UserService;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	public String index(HttpServletRequest request) {
		WebUtils.setSessionAttribute(request, "LOGIN_USER", null);
		return "login/login";
	}

	@RequestMapping(value = "/logsub", method = RequestMethod.POST)
	public String submit(HttpServletRequest request, UserPOJO user) {

		boolean isLogin = false;

		if (EmailValidator.contrast(user.getEmail())) {// 判断用户输入的邮箱是否正确
			user.setPassword(MD5.md5(user.getPassword()));// 密码MD5加密
			UserPOJO userPOJO = userService.login(user);// 数据库查询用户
			if (userPOJO == null || userPOJO.getState() == 0) {// 用户未激活
				// ?????
			}
			if (userPOJO != null) {// 判断用户是否存在
				WebUtils.setSessionAttribute(request, "LOGIN_USER", userPOJO);// 将用户保存到Session中
				isLogin = true;
			}
		}

		if (isLogin) {// 登录成功
			return "redirect:/index";
		}

		return "redirect:/login";
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request) {
		WebUtils.setSessionAttribute(request, "LOGIN_USER", null);
		return "redirect:/login";
	}

}
